import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
})

service.interceptors.request.use(
  (config) => {
    const token = store.getters.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const { data, message, success } = response.data || {}
    if (success) {
      return data
    } else {
      Message({ type: 'error', message: message || 'Operation failed' })
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  async (error) => {
    console.error('Response error:', error)
    Message({ type: 'error', message: error.message || 'Network error' })
    return Promise.reject(error)
  }
)

export default service
